<?php
/**
 * Created by PhpStorm.
 * User: George
 * Date: 2017/9/25
 * Time: 11:06
 */

namespace AdminBundle\Report;

use AdminBundle\Entity\BaseWebchatMember;

/**
 * 新增联系人信息
 * Class ContactUploadTask
 * @package AdminBundle\Task
 */
class NewContactTask extends Task
{
    public function report()
    {
        $wechat = $this->task;
        $new_members = isset($wechat['new_member']) ? $wechat['new_member'] : [];
        $member_count = $this->newMember($wechat['username'], $new_members);

        return $member_count;
    }

    /**
     * 成员好友更新，新增
     * @param $webchatId
     * @param $members
     * @return int
     */
    private function newMember($webchatId, &$members)
    {
        $count = 0;
        if (empty($members) || empty($webchatId)) {
            return $count;
        }
        $em = $this->em;
        if (!is_integer($webchatId)) {
            $webchatUser = $em->getRepository('AdminBundle:BaseWebchatUser')->findOneBy(['userName' => $webchatId]);
            if ($webchatUser == null) {
                return $count;
            }
            $webchatId = $webchatUser->getId();
        }

        // 添加成员好友
        foreach ($members as $member) {
            $webchatMember = $em->getRepository('AdminBundle:BaseWebchatMember')->findOneBy([
                'webchatUserId' => $webchatId,
                'userName' => $member['username']
            ]);
            if ($webchatMember == null) {
                $webchatMember = new BaseWebchatMember();

                $webchatMember->setCtime(new \DateTime())
                    ->setIp($this->ip)
                    ->setCreator($this->username)
                    ->setWebchatUserId($webchatId)
                    ->setUserName($member['username']);

                // 标注用户的类型[熟人好友,营销好友,名片好友]和标签[宝妈,股票];
                $logNewMember = $em->getRepository('AdminBundle:LogNewMember')->findOneBy([
                    'webchatId' => $webchatId,
                    'userName' => $member['username']
                ]);

                if ($logNewMember != null) {
                    $webchatMember
                        ->setSourceType($logNewMember->getSourceType())
                        ->setTags($logNewMember->getTags());
                }
            }

            $webchatMember->setNickname($member['nickname'])
                ->setRemarkName($member['remarkname'])
                ->setType($member['type'])
                ->setTypeText($member['type_text'])
                ->setMobile($member['mobile'])
                ->setSignature($member['signature'])
                ->setProvince($member['province'])
                ->setCity($member['city'])
                ->setCountry($member['country'])
                ->setSex($member['sex'])
                ->setIsContact($member['is_contact']);
            $em->persist($webchatMember);
            $count++;
        }
        $em->flush();
        return $count;
    }

}